package db

import (
	"github.com/zeromicro/go-zero/core/logx"
	xb "xorm.io/builder"
)

func GetData(target interface{}) bool {
	has, err := engine.Get(target)
	if err != nil {
		return false
	} else if !has {
		return false
	}
	return true
}

func ExistData(target interface{}) bool {
	has, err := engine.Exist(target)
	if err != nil {
		return false
	} else if !has {
		return false
	}
	return true
}

func ExistWhereData(target interface{}, where xb.Cond) bool {
	has, err := engine.Where(where).Exist(target)
	if err != nil {
		return false
	} else if !has {
		return false
	}
	return true
}

func FindDatasDesc(target interface{}, where xb.Cond) bool {
	return FindDatas(target, where, "id DESC")
}

func FindDatasAsc(target interface{}, where xb.Cond) bool {
	return FindDatas(target, where, "id ASC")
}

func FindDatas(target interface{}, where xb.Cond, order string) bool {
	if order == "" {
		order = "id DESC"
	}
	err := engine.Where(where).OrderBy(order).Find(target)
	return err == nil
}

func FindPageDatas(target interface{}, where xb.Cond, page int) bool {
	pageSize := 20
	offset := (page - 1) * pageSize
	err := engine.Where(where).Limit(pageSize, offset).Desc("id").Find(target)
	return err == nil
}

func InsertData(target interface{}) bool {
	_, err := engine.Insert(target)
	if err != nil {
		logx.Error(err)
	}
	return err == nil
}

func UpdateData(target interface{}, where xb.Cond) bool {
	_, err := engine.Where(where).Update(target)
	return err == nil
}

func DeleteData(target interface{}) bool {
	_, err := engine.Delete(target)
	return err == nil
}

func CountData(target interface{}, where xb.Cond) int64 {
	total, err := engine.Where(where).Count(target)
	if err != nil {
		return -1
	}
	return total
}
